#!/usr/bin/
# -*- coding: UTF-8 -*-
import os
import xml.etree.cElementTree as ET
from pprint import pprint

from common.global_logger import logger
from utils.file_utils import get_filepath_by_type


def parse_xml(path):
    """
    解析xml文件，将元素信息存到字典中
    @path 根目录文件
    @return elements 返回字典
    """
    elements = {}
    if os.path.exists(path):
        # 找到某个文件夹，和 里面的子文件夹，所有的.xml后缀的文件
        f = get_filepath_by_type(path, "xml", all_files=[])
        for fi in f:
            tree = ET.ElementTree(file=fi)  # 根据xml文件创建elementTree对象.

            # 根据xml文件中的locator找到所有的定位器.
            for elem in tree.iter(tag="locator"):
                locator = elem.attrib  # 元素属性的字典
                # 定位器的名字
                locator_name = locator['name']
                # 需要保证locator_name唯一
                if locator_name in elements.keys():
                    logger.error("xml中元素name有重复，重复名：%s" % locator_name)
                    raise RuntimeError('elements duplicate')
                else:
                    elements[locator_name] = locator
        return elements


if __name__ == '__main__':
    path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, "elements"))
    pprint(parse_xml(path))

    pass
